# encoding: utf-8
import mysql.connector


def connect_mysql(host='localhost', user='root',
                  password='liurusi321', database='weibo', charset='utf8mb4'):
    """
    # mysql连接工具
    argments:
        host: 地址
        user: 用户名
        password: 密码
        database: 数据库
        charset: 链接编码
    """
    return mysql.connector.connect(
        host=host, user=user, password=password, database=database,
        charset=charset
    )


def generate_cursor(mysql_connect, dictionary=True, buffered=True):
    """
    游标
    argments:
        mysql_connect: mysql.connector.connect
        dictionary: 是否字典化
        buffered: 是否启用缓存
    """
    return mysql_connect.cursor(dictionary=dictionary, buffered=buffered)


# 测试
def test():
    conn = connect_mysql()
    cursor = generate_cursor(conn)
    SELECT_SQL = """
        SELECT id FROM suningyigou where user_id={user_id}
    """
    # cursor.execute(SELECT_SQL.format(user_id=2139867665))
    # rst = cursor.fetchall()
    # print rst,type(rst)
    # for i in rst:
    # print i,type(i)
    # conn.close()
    INSERT_SQL = """
        INSERT INTO suningyigou (user_id) VALUES ({user_id})
    """
    try:
        cursor.execute(INSERT_SQL.format(user_id=3182772942))
    except mysql.connector.errors.IntegrityError:
        print 'yes catch error'
    except Exception, e:
        print e
        print type(e)


# test()

